//
//  ST_UIImage+FW.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/20.
//  Copyright © 2019 DouLei. All rights reserved.
//

import Foundation
import Vision
import SDWebImage


extension UIImage {
    
    
    
    func alpha(_ value:CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
    
    func resize_image(targetHeight: CGFloat) -> UIImage {
        
        let size = self.size
        
        let widthRatio  = targetHeight  / size.height
        
        // Figure out what our orientation is, and use that to form the rectangle
        let newSize  = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        
        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        
        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    func resize_image(targetWidth: CGFloat) -> UIImage {
        
        let size = self.size
        
        let widthRatio  = targetWidth  / size.width
        
        // Figure out what our orientation is, and use that to form the rectangle
        let newSize  = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        
        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        
        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    func fix_orientation() -> UIImage {
        let img = self
        if (self.imageOrientation == .up) {
            return img
        }
        
        UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
        let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
        img.draw(in: rect)
        
        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        return normalizedImage
    }
    
    func perform_text_recognition(completion: @escaping (([String]?) -> Void)){
        
        
        // Create a new image-request handler.
        if #available(iOS 13.0, *) {
            
            // Get the CGImage on which to perform requests.
            guard let cgImage = self.cgImage else { return }
            
            let requestHandler = VNImageRequestHandler(cgImage: cgImage)
            
            // Create a new request to recognize text.
            let request = VNRecognizeTextRequest { (request: VNRequest, error: Error?) in
                
                    guard let observations =
                            request.results as? [VNRecognizedTextObservation] else {
                        
                        completion(nil)
                        
                        return
                    }
                    let recognizedStrings = observations.compactMap { observation in
                        // Return the string of the top VNRecognizedText instance.
                        return observation.topCandidates(1).first?.string
                    }
                
                completion(recognizedStrings)
            }
            request.recognitionLanguages = ["zh-Hans"]
            
            do {
                // Perform the text-recognition request.
                try requestHandler.perform([request])
            } catch {
                print("Unable to perform the requests: \(error).")
                completion(nil)
            }
        }else{
            
            completion(nil)
        }
    }
    
    func read_q_r_code_string() -> [String] {
        
        var array = [String]()
        
        guard let detector = CIDetector(ofType: CIDetectorTypeQRCode,
                                        context: nil,
                                        options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]),
              let ciImage = CIImage(image: self),
              let features = detector.features(in: ciImage) as? [CIQRCodeFeature] else {
            return array
        }
        
        for feature in features {
            guard let indeedMessageString = feature.messageString else {
                continue
            }
            array.append(indeedMessageString)
        }
        
        return array
    }
    
}




//MARK: - 上传图片相关
extension UIImage{
    
    
    func tian_uploadImageData()->Data?{
        
        
        var format = self.sd_imageFormat
        
        if format == .HEIC || format == .HEIF{
            
            format = .JPEG
        }
        /// 压缩质量 0.1-1
        let quality = SCComponets.asset_config.upload_compress_value.double
        
        return self.sd_imageData(as: format, compressionQuality: quality)
        
    }
    
    func tian_uploadFileKey()->String{
        
        var fileKey =  UUID().uuidString + "zzz"
        
        switch self.sd_imageFormat {
        case .GIF:
            fileKey += ".gif"
        case .HEIC:
//            fileKey += ".heic"
            fileKey += ".jpeg"
        case .HEIF:
//            fileKey += ".heif"
            fileKey += ".jpeg"
        case .JPEG:
            fileKey += ".jpeg"
        case .PNG:
            fileKey += ".png"
        case .SVG:
            fileKey += ".svg"
        case .TIFF:
            fileKey += ".tiff"
        case .webP:
            fileKey += ".webP"
        default:
            break
        }
        
        return fileKey
    }
    
    /**
     压缩并保存到SDImage 存储
     返回 SDImageCache 的 key
     */
    func compress_with_cache_s_d_image()->String{
        
        
//        let c = (BTianConfigSchema.shared.upload_compress_value * 10).int
//
//        let quality = c.double/10.0
//
//        let compressedData = self.sd_imageData(as: self.sd_imageFormat, compressionQuality: quality)
    
        let fileKey = tian_uploadFileKey()
        
//        let copyImg = UIImage.sd_image(with: compressedData)
        
//        print("用第三方库保存地址:",SDImageCache.shared.diskCachePath)
                
        SDImageCache.shared.store(self, forKey: fileKey) {
            
            if let path = SDImageCache.shared.cachePath(forKey: fileKey){
                print("用第三方库保存 operation is finished:",path)
            }else{
                print("用第三方库保存 operation is finished")
            }
        }
        
        
        return fileKey
    }
    
    
    /**
     保存到 临时目录
     */
    func save_to_b_t_temporary_directory()->String?{
        
        let filename = UUID().uuidString+".png"
        
        guard var path = SC.push_peculiarity_directory else { return nil }
        
        path.appendPathComponent(filename)
        
        
        if let data = self.jpegData(compressionQuality: 1.0) {
            do {
                try data.write(to: path)
            } catch {
                print("error saving file to documents:", error)
                return nil
            }
        }
        return filename
        
    }
    
}
